//app.js
const remoteServerPath = "https://www.laypig.com/";


App({
  data: {
    audioPath: {
      audio_good: "/pages/resource/audio/study/japanese/good.mp3",
      audio_error: "/pages/resource/audio/study/japanese/error.mp3",
      audio_click: "/pages/resource/audio/study/japanese/click.mp3"
    }
  },
  onLaunch: function () {
    this.validationLogin() 
  },
  onShow: function() {
    var that = this

    var currentPages = getCurrentPages()

    if(currentPages && currentPages.length > 0 && currentPages[currentPages.length - 1 ].route != "pages/index/index") {
      wx.reLaunch({
        url: '/pages/index/index',
        success: function () {
          that.validationLogin() 
        }
      })
    }else {
      that.validationLogin()
    }


  },
  onHide: function() {
    wx.clearStorage()
  },
  validationLogin: function(obj) {
    // 获取登录信息
    var loginUserInfo = wx.getStorageSync('loginUserInfo')
    var loginSession = wx.getStorageSync('loginSession')

    if (loginSession) {

      var session_key = loginSession.session_key

      //校验session
      this.validationSession(session_key, loginUserInfo);
    } else {

      // 获取用户信息
      wx.getSetting({
        success: res => {
          if (res.authSetting['scope.userInfo']) {
            wx.getUserInfo({
              withCredentials: false,
              success: res => {
                this.login(res.userInfo)

              }
            })

          }
        }
      })
    }

    //回调函数
    if (obj && obj.callback) {
      obj.callback()
    }

  },
  login: function(option, fun) {
    var that = this
    that.showLoading("登录中");
    // 登录
    wx.login({
      timeout: 8000,
      success: res => {

        option.code = res.code

        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        wx.request({
          url: remoteServerPath + 'api/wechat/login.do',
          data: option,
          method: 'GET',
          header: { 'content-type': 'application/x-www-form-urlencoded' },
          success: function (res) {
            var data = res.data;

            if( data.success ) {
              //缓存login session
              var loginSession = wx.getStorageSync('loginSession') || {}
              var loginUserInfo = wx.getStorageSync('loginUserInfo') || {}

              loginUserInfo = data.result
              
              loginSession.session_key = data.attributes["session_key"]

              wx.setStorageSync('loginSession', loginSession)
              wx.setStorageSync('loginUserInfo', loginUserInfo)
              
              if (that.userInfoReadyCallback) {
                that.userInfoReadyCallback(loginUserInfo)
              }

              that.showToast("登录成功")

            }else {
              that.showToast("登录失败")
              console.log(res)
            }

          },
          fail: function (res) {
            that.showToast("登录请求失败")
            console.log(res)
          },
          complete: function() {
            that.hideLoading();
          }

        })
      },
      fail: res => {
        console.log(res)
        console.log("code获取失败")
      }
    })
  },
  validationSession: function (session_key, loginUserInfo) {
    
    var that = this
    
    wx.request({
      url: remoteServerPath + 'api/wechat/validation.do',
      data: { session_key: session_key},
      method: 'GET',
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      success: function (res) {
        var data = res.data
        //session过期的话，重新登录
        if(!data.success) {
          // 获取用户信息
          wx.getSetting({
            success: res => {

              if (res.authSetting['scope.userInfo']) {

                wx.getUserInfo({
                  withCredentials: false,
                  success: res => {
                    that.login(res.userInfo)
                  }
                })

              }
            }
          })
        }else {
          
          if (that.userInfoReadyCallback) {
            that.userInfoReadyCallback(loginUserInfo)
          }
        }

      },
      fail: function (res) {
        console.log('submit fail');
      }

    })
  },
  globalData: {
    userInfo: null,
    remoteServerPath: "https://www.laypig.com/"
  },
  containString: function (answer, ask) {

    let result = false;

    if (null != answer && null != ask && "" != answer && "" != ask) {
      if (ask.indexOf(answer) != -1) {
        result = true;
      }
    }

    return result;

  },
  equalString: function(str1, str2) {

    let result = false;

    if(null != str1 && null != str2 && "" != str1 && "" != str2) {
      if(str1 === str2) {
        result = true;
      }
    }

    return result;

  },
  equalNumber: function(num1, num2) {
    let result = false;

    if (null != num1 && null != num2 && !isNaN(num1) && !isNaN(num2)) {
      if (num1 === num2) {
        result = true;
      }
    }

    return result;
  },
  playBackgroundAudio: function(path) {
    var innerAudioContext = wx.createInnerAudioContext()
    innerAudioContext.autoplay = true
    innerAudioContext.src = path
    innerAudioContext.onPlay(() => {
    })
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })
    innerAudioContext.onEnded(() => {
      innerAudioContext.destory;
    })
  },
  showToast: function (title) {
    wx.showToast({
      title: title,
      icon: 'success',
      duration: 800
    });
  },
  alert: function(title) {
    wx.showModal({
      content: title,
      showCancel: false,
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
        }
      }
    });
  },
  showLoading: function(title) {
    wx.showLoading({
      title: title,
      mask: true
    })
  },
  hideLoading: function() {
    wx.hideLoading()
  }
})